﻿@model ESN.Models.Exercise
@{
    ViewBag.Title = "Create New Test";
    ViewData["header"] = "<link href=\"" + Url.Content("~/Content/esnQuiz.css") + "\" rel=\"stylesheet\" type=\"text/css\" />";
    
}
        <script src="@Url.Content("~/Scripts/esnQuiz-create.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jstorage.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
		<script type="text/javascript">
		    $(document).ready(function () {
		        //******//
		        //markup some
		        $(window).bind("beforeunload", function () { return "Do you really want to close?"; });
		        $("#buttonUpdate").hide();
		        $("#newCat").hide();
		        $("#dialog:ui-dialog").dialog("destroy");
		        $("#submitedDialog").dialog({ autoOpen: false,
		            modal: true,
		            width: "80%",
		            maxWidth: "80%",
		            open: function () { RetrieveData() },
		            close: function () { $("#newCat").hide() }
		        });
		        $("#ExLimitTimeDiv").hide();

		        var type = 0;
		        var questionList = new Array();
		        questionList = $.parseJSON('@Html.Raw(ViewBag.Ques)');
		        var corrTmp = $.parseJSON('@Html.Raw(ViewBag.Corr)');
                for(i = 0; i < questionList.length; i++)
                {
                    questionList[i].correct = corrTmp[i];
                }
		        currentEditor = new EditorType0($("#mainEditor"));
		        delete currentEditor;
		        currentEditor = new EditorType0($("#mainEditor"));
		        currentEditor.Show();
		        QuestionListReset();

		        //begin "Switching Question List and Editor Area"
		        $("#questionList").animate({ width: "toggle" }, 0);

		        $("#toggleBar").click(function () {
		            $("#editorArea").animate({ width: "toggle" }, "medium");
		            $("#questionList").animate({ width: "toggle" }, "medium");
		        });

		        //begin "Switching Editor Type"
		        $("#buttonSave").click(function () {
		            var currentData = currentEditor.Render();

		            if (currentData.numAns < 1 && currentData.type != 4) {
		                alert("no ansewr???");
		                return false;
		            }

		            if ((currentData.type == 4) && (parseInt(currentData.max) < parseInt(currentData.min))) {
		                alert("Invailid input. Maxlenght must bigger than MinLenghht");
		                return false;
		            }
		            questionList.push(currentData);
		            $("#questionList").empty();
		            QuestionListReset();
		            type = $("#typeSelector").val();
		            ChangeCurrentEditor(parseInt(type));
		            currentEditor.Show();
		        });

		        //begin buttonChange click
		        $("#buttonChange").click(function () {
		            var currentData = currentEditor.Render();
		            if ((currentData.type == 4) && (parseInt(currentData.max) < parseInt(currentData.min))) {
		                alert("Invailid input. Maxlenght must bigger than MinLenghht");
		                return false;
		            }
		            type = $("#typeSelector").val();
		            ChangeCurrentEditor(parseInt(type));
		            currentEditor.Show();
		        });

		        //begin buttonSubmit click
		        $("#buttonSubmit").click(function () {
		            $("#submitedDialog").dialog("open");
		        });

		        //Begin buttonConfirm click
		        var correctList = new Array();
		        $("#buttonConfirm").click(function () {
		            $('form').removeData("validator");
		            $("form").removeData("unobtrusiveValidation");
		            $.validator.unobtrusive.parse("form");
		            if ($('form').valid() == false)
		                return false;

		            $(this).attr("disabled", "disabled");
		            $(window).unbind("beforeunload");

		            var exercise = new Object();
		            exercise.ExName = $("#ExName").val();

		            if (correctList.length == 0) {
		                for (i = 0; i < questionList.length; i++) {
		                    correctList.push(questionList[i].correct);
		                    delete questionList[i].correct;
		                }
		            }
		            exercise.ExId = @Model.ExId;
		            exercise.ExCorrect = JSON.stringify(correctList);
		            exercise.CatId = $(":radio[name=radioCatLevel2]:checked").val();
		            exercise.ExContent = JSON.stringify(questionList);
		            exercise.ExCreateTime = "2014-01-06T15:45:00";
		            exercise.ExPublic = false;
		            exercise.ExFreeShot = false;
		            exercise.ExTrace = false;
                    exercise.UserId = '@Model.UserId';

		            if ($("#ExPublic").is(':checked')) {
		                exercise.ExPublic = true;
		            }

		            if ($("#ExFreeShot").is(':checked')) {
		                exercise.ExFreeShot = true;
		            }

		            if ($("#ExTrace").is(':checked')) {
		                exercise.ExTrace = true;
		            }

		            exercise.ExShot = $("#ExShot").val();

		            //Not completed yet
		            if ($("#ExLimitTime").is(':checked')) {
		                exercise.ExTime = $('#ExTimeH').val() * 60 + $('#ExTimeM').val();
		            }

		            $.ajax({
		                type: "PUT",
		                contentType: "application/json; charset=utf-8",
		                dataType: "json",
		                url: "/QuizService.svc/Exercises(@Model.ExId)/",
		                data: JSON.stringify(exercise),
		                success: function (data, textStatus, jqXHR) {
		                    window.location.reload();
		                },
		                error: function (jqXHR, textStatus, errorThrown) {
		                    alert(errorThrown + "\nYour data not submit yet. Check the conection and submit agian.");
		                    $("#buttonConfirm").removeAttr("disabled");
		                }
		            });
		        });

		        //cretae new catergory
		        $("#newCatCreate").click(function () {
		            if ($("input[name=radioCatLevel1]").is(":checked") && $("#newCatName").val().length > 1) {
		                var cat = new Object();
		                cat.ParentId = $("input[name=radioCatLevel1]").val();
		                cat.CatName = $("#newCatName").val();
		                cat.CatPublic = true;
		                cat.CatTime = "2014-01-06T15:45:00";
		                $.ajax({
		                    type: "POST",
		                    contentType: "application/json; charset=utf-8",
		                    dataType: "json",
		                    url: "/QuizService.svc/Categories/",
		                    data: JSON.stringify(cat),
		                    success: function (data, textStatus, jqXHR) {
		                        var line = '<div><input type="radio" name="radioCatLevel1" data-val="true" data-val-required="Phải chọn 1 chủ đề." class="catLevel1" value="' + data.d.CatId + '" />' + data.d.CatName + '</div>';
		                        $("#catLevel2").append(line);
		                        $("#newCatName").val("");
		                    },
		                    error: function (jqXHR, textStatus, errorThrown) {
		                        alert(errorThrown + "\nYour data not submit yet. Check the conection and submit agian.");
		                    }
		                });
		            }
		        });

		        //begin "Push data back" fucntion
		        $(".quesTitle").live("click", function () {
		            type = $(this).attr("dataType");
		            index = $(this).attr("dataIndex");
		            $("#editorArea").animate({ width: "toggle" }, "medium");
		            $("#questionList").animate({ width: "toggle" }, "medium");
		            ChangeCurrentEditor(parseInt(type));
		            currentEditor.Render(questionList[index]);
		            $("#buttonSave").hide();
		            $("#buttonChange").hide();
		            $("#buttonSubmit").hide();
		            $("#buttonUpdate").show();
		        });
		        $("#buttonUpdate").click(function () {
		            $(this).hide();
		            $("#buttonSave").show();
		            $("#buttonChange").show();
		            $("#buttonSubmit").show();
		            var currentData = currentEditor.Render();
		            questionList[index] = currentData;
		            //alert("Shit" + JSON.stringify(questionList));
		            QuestionListReset();
		            type = $("#typeSelector").val();
		            ChangeCurrentEditor(parseInt(type));
		            currentEditor.Show();
		        });

		        //begin "Change Editor function"
		        function ChangeCurrentEditor(t) {
		            currentEditor.Hide();
		            $("#mainEditor").empty();
		            delete currentEditor;
		            switch (t) {
		                case 4:
		                    currentEditor = new EditorType4($("#mainEditor")); ;
		                    break;
		                case 3:
		                    currentEditor = new EditorType3($("#mainEditor")); ;
		                    break;
		                case 2:
		                    currentEditor = new EditorType2($("#mainEditor")); ;
		                    break;
		                case 1:
		                    currentEditor = new EditorType1($("#mainEditor")); ;
		                    break;
		                default:
		                    currentEditor = new EditorType0($("#mainEditor")); ;
		            }
		        }

		        //begin "Reset Question List" function
		        function QuestionListReset() {
		            $("#questionList").empty();
		            for (i = 0; i < questionList.length; i++) {
		                $("#questionList").append($("<div></div>", {
		                    class: "quesTitle Type" + questionList[i].type,
		                    dataType: questionList[i].type,
		                    dataIndex: i
		                }).text(questionList[i].ques));
		            }
		        }

		        //begin "Retrieve Data" function
		        function RetrieveData() {
		            var query = "/QuizService.svc/Categories?$filter=ParentId%20eq%20null";
		            $.getJSON(query, function (result) {
		                $("#catLevel1").empty();
		                $.each(result.d, function (i, item) {
		                    var line = '<div><input type="radio" name="radioCatLevel1" data-val="true" data-val-required="Phải chọn 1 chủ đề." class="catLevel1" value="' + item.CatId + '" />' + item.CatName + '</div>';
		                    $("#catLevel1").append(line);
		                });
		            });
		        }

		        //begin Checkbox class Catlevel1 click
		        $(".catLevel1").live("click", function () {
		            $("#catLevel2").empty();
		            var query = "/QuizService.svc/Categories?$filter=ParentId%20eq%20" + $(this).val();
		            $.getJSON(query, function (result) {
		                $.each(result.d, function (i, item) {
		                    var line = '<div><input type="radio" name="radioCatLevel2" data-val="true" data-val-required="Phải chọn 1 chuyên mục." value="' + item.CatId + '" />' + item.CatName + '</div>';
		                    $("#catLevel2").append(line);
		                });
		            });
		            $("#newCat").show();
		        });


		        //begin ExLimitTime, ExLimitShot change
		        $("#ExLimitTime").change(function () {
		            if ($(this).is(':checked'))
		                $("#ExLimitTimeDiv").show();
		            else
		                $("#ExLimitTimeDiv").hide();
		        });

		        //******//
                type = questionList[0].type;
                index = 0;
                ChangeCurrentEditor(type);
		        currentEditor.Render(questionList[index]);
		        $("#buttonSave").hide();
		        $("#buttonChange").hide();
		        $("#buttonSubmit").hide();
		        $("#buttonUpdate").show();
		    });		
		</script>
        <h1>@ViewBag.Title</h1>
        <div id="submitedDialog">
            <div id="submitDialogSttus"></div>
            <form action="#">
                <table style="width : 100%;border : solid thin;">
                    <tr style="vertical-align:text-top">
                        <td style="width : 33%;border-right:thick double;" id="catLevel1">
                            <span class="field-validation-valid" data-valmsg-for="radioCatLevel1" data-valmsg-replace="true"></span>
                        </td>
                        <td style="width : 33%;border-right:thick double;">
                            <span class="field-validation-valid" data-valmsg-for="radioCatLevel2" data-valmsg-replace="true"></span>
                            <div id="catLevel2"></div>
                            <hr />
                            <div id="newCat">
                                <div>@ESN.Languages.LangString.Load("new_cat", "Quiz")</div>
                                <input type="text" id="newCatName" />
                                <input type="button" id="newCatCreate" value="@ESN.Languages.LangString.Load("save", "Home")" />
                            </div>
                        </td>
                        <td style="width : 33%;" id="ExInfo">
                        
                                <div>
                                    @ESN.Languages.LangString.Load("name", "Quiz") <input type="text" id="ExName" name="ExName" class="text-box single-line" data-val="true" data-val-required="The a field is required." value="@Model.ExName" />
                                    <span class="field-validation-valid" data-valmsg-for="ExName" data-valmsg-replace="true"></span>
                                </div>
                                <div>@ESN.Languages.LangString.Load("public", "Quiz") <input type="checkbox" id="ExPublic" checked="checked" /></div>
                                <div>@ESN.Languages.LangString.Load("trace", "Quiz") <input type="checkbox" id="ExTrace" checked="checked" /></div>
                                <div>@ESN.Languages.LangString.Load("time_limit", "Quiz") <input type="checkbox" id="ExLimitTime" /></div>
                                <div id="ExLimitTimeDiv">
                                    <input type="text" value="1" id="ExTimeH" name="ExTimeH" size="2" class="text-box single-line" data-val="true" data-val-required="The a field is required." data-val-range="(0 - 65535)" data-val-range-max="65535" data-val-range-min="0" data-val-number="The field b must be a number." /> @ESN.Languages.LangString.Load("hour", "Quiz")
                                    <input type="text" value="0" id="ExTimeM" name="ExTimeM" size="2" class="text-box single-line" data-val="true" data-val-required="The a field is required." data-val-range="(0 - 59)" data-val-range-max="59" data-val-range-min="0" data-val-number="The field b must be a number." /> @ESN.Languages.LangString.Load("minute", "Quiz")
                                </div>
                                <div id="ExLimitShotDiv">@ESN.Languages.LangString.Load("shot", "Quiz") <input type="text" id="ExShot" value="1" size="2" class="text-box single-line" /></div>
                                <div>@ESN.Languages.LangString.Load("free_shot", "Quiz")<input type="checkbox" id="ExFreeShot" checked="checked"/></div>
                                <input type="button" id="buttonConfirm" value="Confirm" />
                        
                        </td>
                    </tr>
                </table>
            </form>
        </div>
        <div id="questionList" class="ui-widget-content ui-corner-all"></div>
        <div id="toggleBar" class="ui-state-active">Q<br />u<br />e<br />s<br />t<br />i<br />o<br />n<br /><br />L<br />i<br />s<br />t</div>
        <div id="editorArea">
            <div class="ui-widget-header ui-corner-top">
				<select id="typeSelector">
					<option value="0">@ESN.Languages.LangString.Load("single", "Quiz")</option>
					<option value="1">@ESN.Languages.LangString.Load("multi", "Quiz")</option>
					<option value="2">@ESN.Languages.LangString.Load("col_match", "Quiz")</option>
					<option value="3">@ESN.Languages.LangString.Load("gap_filling", "Quiz")</option>
					<option value="4">@ESN.Languages.LangString.Load("essay", "Quiz")</option>
				</select>
				<input type="button" value="@ESN.Languages.LangString.Load("change", "Quiz")" id="buttonChange" />
				<input type="button" value="@ESN.Languages.LangString.Load("save_add", "Quiz")" id="buttonSave" />
				<input type="button" value="@ESN.Languages.LangString.Load("update_add", "Quiz")" id="buttonUpdate" />
				<input type="button" value="@ESN.Languages.LangString.Load("submit", "Quiz")" id="buttonSubmit" />
			</div>
			<div id="mainEditor" class="ui-widget-content ui-corner-bottom">
			</div>
        </div>